<template>
    <div>
        <van-popup v-model="visible" :style="{ padding: '10px', width: '80vw', height: '80vh' }">
            <van-nav-bar :title="keyName" left-text="关闭" @click-left="visible = false;" right-text="添加"
                @click-right="openAdd" />
            <van-row>
                <van-col span="24" style="text-align: center;">
                    <van-checkbox-group v-model="identityChk" direction="horizontal" style="justify-content: center;">
                        <van-checkbox shape="square" right-icon="video-o" name="0" style="margin-bottom: 10px"
                          >识别公库</van-checkbox>
                        <van-checkbox shape="square" right-icon="video-o" name="1"
                            style="margin-bottom: 10px">识别私库</van-checkbox>
                    </van-checkbox-group>
                </van-col>
            </van-row>
            <van-row>
                <van-col span="24">
                    <van-search placeholder="请输入搜索关键词" v-model="searchKeyword" />
                </van-col>
            </van-row>
            <van-row v-for="item in filterManagerList" :key="item.id">
                <van-col span="16" style="font-size:0.37333rem;">
                    <div style="margin-top:10px;">{{ item.keyword }}</div>
                </van-col>
                <van-col span="8">
                    <van-button @click="openEdit(item)" type="primary" size="small"
                        style="float:right;margin-top: 5px;margin-left:5px;">修改</van-button>
                    <van-button type="danger" size="small" style="float:right;margin-top: 5px;"
                        @click="delword(item.id)">删除</van-button>
                </van-col>
            </van-row>
        </van-popup>
        <van-popup v-model="showPhotoDetail" :style="{ padding: '10px', width: '80vw', height: '80vh' }">
            <van-nav-bar :title="keyName + '-' + (editModelType == 'add' ? '添加' : '修改')" left-text="返回"
                @click-left="showPhotoDetail = false;" />
            <van-row>
                <van-col span="24"><van-field label="标题" placeholder="请输入" v-model="editModel.keyword" /></van-col>
                <van-col span="24">
                    <van-field autocomplete="off" name="photos" :label="keyName">
                        <template #input>
                            <van-uploader v-if="propType == 'video'" @click-preview="previewVideos"
                                v-model="uploadFiles" accept="video/*" @delete="deleteUploadFile" :preview-options="{
                                    closeable: true
                                }" :max-count="9" :deletable="true" :show-upload="true" :after-read="afterUpload" />
                            <van-uploader v-if="propType == 'image'" v-model="uploadFiles" accept=".jpg,.jpeg,.png"
                                @delete="deleteUploadFile" :preview-options="{
                                    closeable: true
                                }" :max-count="9" :deletable="true" :show-upload="true" :after-read="afterUpload" />
                        </template>
                    </van-field>
                </van-col>
                <van-col span="24" style="text-align: center;">
                    <van-button type="primary" size="small" @click="saveEdit">保存</van-button>
                    &nbsp;
                    &nbsp;
                    <van-button size="small" @click="showPhotoDetail = false;">关闭</van-button>
                </van-col>
            </van-row>
        </van-popup>
    </div>
</template>
<script>

import { Toast } from 'vant'
import loginType from './loginType';
import { cosUploadImg } from '@/utils/cosUpload.js'
export default {
    name: 'comKeyUploadPopup',
    model: {
        prop: "value",
        event: "change",
    },
    components: {
    },
    props: {
        propName: String,
        propType: String,
        keyId: String,
        keyName: String,
        value: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            isActionSuccessed: false,
            uploadFiles: [],
            editModelType: '',
            editModel: {},
            isInitConfig: false,
            searchKeyword: '',
            identityChk: ['0', '1'],
            showPhotoDetail: false,
            visible: false,
            managerList: []
        }
    },
    computed: {
        filterManagerList() {
            if (this.searchKeyword)
                return this.managerList.filter(m => m.keyword.includes(this.searchKeyword));
            else
                return this.managerList;

        }
    },
    watch: {
        identityChk(val, oldval) {
            if (this.isInitConfig) {
                this.isInitConfig = false;
                return;
            }
            var pubVal = '0';
            var privateVal = '1';
            var v = val.find(m => m == pubVal);
            if (v != oldval.find(m => m == pubVal))
                this.configChange(v == pubVal, false);

            v = val.find(m => m == privateVal);
            if (v != oldval.find(m => m == privateVal))
                this.configChange(v == privateVal, true);
        },
        value(val) {
            //console.log(1,val);
            this.visible = val;
        },
        visible(val) {
            //console.log(2,val);
            this.$emit("change", val);
            if (val) {
                this.initData();
            }
        }
    },
    methods: {

        previewVideos(file, detail) {
            console.warn(file, detail.index)
            // 跨组件通信，使用bus总线。
            this.$bus.$emit('toPreviewAndPlayVideo', file.url)
        },

        configChange(bl, isPrivate) {
            var params1 = {
                propName: this.propName,
                keyName: this.keyName,
                isPrivate: isPrivate
            };
            if (bl) {
                this.$api.keyword.keywordConfigDelete(params1).then(res => {
                    if (res.code === 200 && res.data) {
                        Toast('操作成功！')
                    } else {
                        Toast('系统出错！')
                    }
                })
            } else {
                this.$api.keyword.keywordConfigAdd(params1).then(res => {
                    if (res.code === 200 && res.data) {
                        Toast('操作成功！')
                    } else {
                        Toast('系统出错！')
                    }
                })
            }
        },
        saveEdit() {
            if (this.editModelType == 'add')
                this.addword();
            else
                this.editword();
        },
        // 删除文件预览时，修改数据
        deleteUploadFile(file, detail) {
            if (this.uploadFiles.length === 0) {
                this.uploadFiles = []
            } else {
                // splice方法会改变原始数组
                this.uploadFiles.splice(detail.index, 1)
            }
        },

        // 上传
        afterUpload(picture) {
            console.log('picture参数的file属性', picture.file)
            picture.status = 'uploading'
            picture.message = '上传中...'
            this._reqUploadPicture(picture).then(url => {
                if (!url) {
                    Toast('图片上传失败!')
                    picture.status = 'failed'
                    picture.message = '上传失败'
                } else {
                    picture.status = 'done'
                }
                picture.url = url;
                // 不断的增加
                //this.uploadFiles.push(url)
            })
        },
        openAdd() {
            this.editModelType = 'add';
            this.editModel = {};
            this.uploadFiles = [];
            this.showPhotoDetail = true;
        },
        openEdit(item) {
            this.editModelType = 'edit';
            this.editModel = item;
            if (item.uploadFiles) {
                if (this.propType == 'image')
                    this.uploadFiles = item.uploadFiles.split('|').map(m => {
                        return { url: m, isImage: true }
                    });
                else
                    this.uploadFiles = item.uploadFiles.split('|').map(m => {
                        return { url: m }
                    });
            }
            //console.log("this.uploadFiles", this.uploadFiles)
            this.showPhotoDetail = true;
        },
        initData() {
            //alert("");
            var params1 = {
                propName: this.propName,
                keyName: this.keyName
            };
            var that = this;
            this.$api.keyword.keywordConfigGetConfig(params1).then(res => {
                if (res.code === 200) {
                    var ary = new Array();
                    if (res.data.item1)
                        ary.push('0');
                    if (res.data.item2)
                        ary.push('1');
                    that.isInitConfig = true;
                    that.identityChk = ary;
                } else {
                    Toast('错误！')
                }
            })
            this.getList();
        },
        getList() {
            var isPersionalLogin = loginType.isPrivatePersionLogin();
            var params = {
                isPersionalLogin,
                keyName: this.keyName,
                propName: this.propName
            };
            var that = this;
            this.$api.keyword.keywordList(params).then(res => {
                if (res.code === 200) {
                    if (that.isActionSuccessed) {
                        Toast('操作成功！')
                        that.isActionSuccessed = false
                    }
                    that.managerList = res.data;
                } else {
                    Toast('系统出错！')
                }
            })
        },
        addword() {
            //console.log("this.uploadFiles=", this.uploadFiles)
            if (!this.editModel.keyword) {
                Toast('请填写关键字！')
                return;
            }
            if (this.uploadFiles.length == 0) {
                Toast('请上传文件！')
                return;
            }
            var params = {
                propType: this.propType,
                propName: this.propName,
                keyName: this.keyName,
                keyId: this.keyId,
                isPrivate: loginType.isPrivatePersionLogin(),
                keyword: this.editModel.keyword,
                isSelected: true,
                keywordContent: '',
                isCompare: true,
                uploadFiles: this.uploadFiles.map(m => m.url).join('|')
            };
            var that = this;
            this.$api.keyword.keywordAdd(params).then(res => {
                if (res.code === 200 && res.data) {
                    //Toast('操作成功！')
                    that.isActionSuccessed = true;
                    that.showPhotoDetail = false;
                    that.getList();
                } else {
                    Toast('系统出错！')
                }
            })
        },
        editword(id) {
            var that = this;
            if (!this.editModel.keyword) {
                Toast('请填写关键字！')
                return;
            }
            if (this.uploadFiles.length == 0) {
                Toast('请上传文件！')
                return;
            }

            this.editModel.uploadFiles = this.uploadFiles.map(m => m.url).join('|')
            this.$api.keyword.keywordUpdate(this.editModel).then(res => {

                if (res.code === 200 && res.data) {
                    that.isActionSuccessed = true;
                    that.showPhotoDetail = false;
                    //Toast('操作成功！')
                    that.getList();
                } else {
                    Toast('系统出错！')
                }
            })
        },
        delword(id) {
            var params = {
                id
            };
            var that = this;
            this.$api.keyword.keywordDelete(params).then(res => {
                if (res.code === 200 && res.data) {
                    that.isActionSuccessed = true;
                    that.getList();
                    //Toast('操作成功！')
                } else {
                    Toast('系统出错！')
                }
            })
        },
        async _reqUploadPicture(picture) {
            let formData = new FormData()
            formData.append('filename', picture.file)
            // 公司认证的图片
            const img_type = 'job_environment'
            // const res = await this.$api.uploadImg.uploadPhotos(formData, img_type)
            const res = await cosUploadImg(picture.file, img_type)
            if (res.code === 200) {
                return res.data
            }
        },
    },
    mounted() {
        if (this.value) {
            this.visible = true;
        }
    }
}
</script>

<style scoped>
.colortext::v-deep .van-field__label,
.colortext::v-deep .van-radio__label,
.colortext::v-deep .van-checkbox__label,
.colortext::v-deep .van-field__control {
    color: #323233 !important;
}
</style>
